<template>
  <div class="project-doing-container">

    <!-- 搜索和过滤区域 -->
    <div class="search-filter-section">
      <el-form :inline="true" class="filter-form">
        <!-- 项目名称搜索 -->
        <el-form-item label="项目名称">
          <el-input
              v-model="searchForm.projectName"
              placeholder="请输入项目名"
              prefix-icon="el-icon-search"
              style="width: 190px"
              @keyup.enter.native="handleSearch">
          </el-input>
        </el-form-item>
        
        <!-- 重要程度筛选 -->
        <el-form-item label="重要程度">
          <el-select v-model="searchForm.importantLevel" placeholder="选择重要程度" clearable  style="width: 160px">
            <el-option label="非常重要" value="非常重要"></el-option>
            <el-option label="重要" value="重要"></el-option>
            <el-option label="不重要" value="不重要"></el-option>
          </el-select>
        </el-form-item>

        <!-- 项目类别筛选 -->
        <el-form-item label="项目类别">
          <el-select v-model="searchForm.projectType" placeholder="选择项目类别" clearable style="width: 160px">
            <el-option label="内部项目" value="内部项目"></el-option>
            <el-option label="外部项目" value="外部项目"></el-option>
            <el-option label="研发项目" value="研发项目"></el-option>
          </el-select>
        </el-form-item>

        <!-- 预算范围筛选 -->
        <el-form-item label="预算范围">
          <el-input-number 
            v-model="searchForm.minBudget" 
            :min="0" 
            placeholder="最小预算">
          </el-input-number>
          <span style="margin: 0 8px;">-</span>
          <el-input-number 
            v-model="searchForm.maxBudget" 
            :min="0" 
            placeholder="最大预算">
          </el-input-number>
        </el-form-item>

        <!-- 按钮组 -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
        <!-- 表格区域 -->
        <div class="main-table-section">
      <el-card>
        <div slot="header" class="table-header">
          <div class="left-section">
            <span class="section-title">在途项目列表</span>
          </div>
          <div class="right-section">
            <el-button-group>
              <el-button size="small" @click="refreshData">
                <i class="el-icon-refresh"></i> 刷新
              </el-button>
              <el-button size="small" type="primary" @click="exportToExcel">
                <i class="el-icon-download"></i> 导出
              </el-button>
            </el-button-group>
          </div>
        </div>
        
        <el-table 
          :data="paginatedTableData" 
          style="width: 100%"
          :stripe="true"
          :border="true"
          @sort-change="handleSortChange">
          <el-table-column
              v-for="(value, key, index) in parentsCloums"
              :key="index"
              :label="value.name"
              :prop="value.propName"
              sortable="custom">
          </el-table-column>
          <el-table-column
              label="进度"
              prop="taskProgress"
              sortable="custom">
            <template slot-scope="scope">
              <el-progress
                  type="line"
                  :stroke-width="15"
                  :percentage="scope.row.taskProgress"
                  :status="getProgressStatus(scope.row.taskProgress)">
              </el-progress>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="viewDetails(scope.row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加分页组件 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            :total="filteredTableData.length"
            layout="total, prev, pager, next">
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 项目详情对话框 -->
    <el-dialog title="项目详情" :visible.sync="dialogVisible" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="项目名称">{{ currentProject.projectName }}</el-descriptions-item>
        <el-descriptions-item label="项目类别">{{ currentProject.projectType }}</el-descriptions-item>
        <el-descriptions-item label="重要程度">{{ currentProject.importantLevel }}</el-descriptions-item>
        <el-descriptions-item label="预算金额">{{ currentProject.budget }}</el-descriptions-item>
        <el-descriptions-item label="合同金额">{{ currentProject.contractAmount }}</el-descriptions-item>
        <el-descriptions-item label="项目进度">{{ currentProject.taskProgress }}%</el-descriptions-item>
      </el-descriptions>
      <div class="dialog-footer" slot="footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 图表展示区域 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>项目类型分布</span>
          </div>
          <div class="chart-container" ref="pieChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>项目进度一览</span>
          </div>
          <div class="progress-list">
            <div v-for="(project, index) in tableData" 
                 :key="index" 
                 class="progress-item">
              <div class="progress-header">
                <span class="project-name" :title="project.projectName">
                  {{ project.projectName }}
                </span>
                <span class="progress-value">{{ project.taskProgress }}%</span>
              </div>
              <el-progress 
                :percentage="project.taskProgress"
                :status="getProgressStatus(project.taskProgress)"
                :stroke-width="15">
              </el-progress>
              <div class="progress-footer">
                <el-tag size="mini" :type="getProjectTypeTag(project.projectType)">
                  {{ project.projectType }}
                </el-tag>
                <span class="project-budget">预算: ¥{{ project.budget }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import http from "@/api/http";
import * as echarts from 'echarts';
import * as XLSX from 'xlsx';

export default {
  name: "ProjectDoing",
  data() {
    return {
      searchForm: {
        projectName: '',
        importantLevel: '',
        projectType: '',
        minBudget: '',
        maxBudget: ''
      },
      parentsCloums: [ //表头
        {
          name: "项目名称",
          propName: "projectName",
        }, {
          name: "合同额",
          propName: "contractAmount",
        }, {
          name: "重要程度",
          propName: "importantLevel",
        },{
          name: "预算",
          propName: "budget",
        },{
          name: "项目类别",
          propName: "projectType",
        }
      ],
      tableData: [],
      dialogVisible: false,
      currentProject: {},
      pieChart: null,
      lineChart: null,
      currentPage: 1,
      pageSize: 11,  // 每页显示11条数据
    }
  },
  computed: {
    filteredTableData() {
      return this.tableData.filter(item => {
        // 项目名称筛选
        const nameMatch = !this.searchForm.projectName || 
          item.projectName.toLowerCase().includes(this.searchForm.projectName.toLowerCase());

        // 重要程度筛选
        const levelMatch = !this.searchForm.importantLevel || 
          item.importantLevel === this.searchForm.importantLevel;

        // 项目类别筛选
        const typeMatch = !this.searchForm.projectType || 
          item.projectType === this.searchForm.projectType;

        // 预算范围筛选
        const budgetMatch = (!this.searchForm.minBudget || item.budget >= this.searchForm.minBudget) && 
          (!this.searchForm.maxBudget || item.budget <= this.searchForm.maxBudget);

        return nameMatch && levelMatch && typeMatch && budgetMatch;
      });
    },
    totalBudget() {
      return this.tableData.reduce((sum, project) => sum + (project.budget || 0), 0).toLocaleString();
    },
    averageProgress() {
      if (this.tableData.length === 0) return 0;
      const total = this.tableData.reduce((sum, project) => sum + (project.taskProgress || 0), 0);
      return Math.round(total / this.tableData.length);
    },
    delayedProjects() {
      return this.tableData.filter(project => project.taskProgress < 50).length;
    },
    paginatedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredTableData.slice(start, end);
    }
  },
  methods: {
    getinfo() {
      http.get("/api/projects/ongoing")
          .then(res => {
            this.tableData = res;
          })
    },
    handleSearch() {
      // 使用计算属性自动过滤，无需额外处理
    },
    resetSearch() {
      this.searchForm = {
        projectName: '',
        importantLevel: '',
        projectType: '',
        minBudget: '',
        maxBudget: ''
      };
      this.currentPage = 1;  // 重置页码
      this.getinfo();
    },
    refreshData() {
      this.getinfo();
    },
    getProgressStatus(progress) {
      if (progress >= 80) return 'success';
      if (progress >= 50) return '';
      return 'exception';
    },
    getProjectTypeTag(type) {
      const typeMap = {
        '内部项目': 'info',
        '外部项目': 'warning',
        '研发项目': 'success'
      };
      return typeMap[type] || 'info';
    },
    viewDetails(row) {
      this.currentProject = row;
      this.dialogVisible = true;
    },
    editProject(row) {
      // 实现编辑功能
    },
    handleSortChange({ prop, order }) {
      // 实现排序功能
    },
    exportToExcel() {
      // 使用过滤后的数据
      const dataToExport = this.filteredTableData.map(item => {
        // 根据表头定义导出的数据结构
        return {
          '项目名称': item.projectName,
          '合同额': item.contractAmount,
          '重要程度': item.importantLevel,
          '预算': item.budget,
          '项目类别': item.projectType,
          '项目进度': item.taskProgress + '%'
        };
      });

      // 创建工作簿
      const worksheet = XLSX.utils.json_to_sheet(dataToExport);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '在途项目');

      // 设置列宽
      const columnWidths = [
        { wch: 20 }, // 项目名称
        { wch: 12 }, // 合同额
        { wch: 10 }, // 重要程度
        { wch: 12 }, // 预算
        { wch: 10 }, // 项目类别
        { wch: 10 }  // 项目进度
      ];
      worksheet['!cols'] = columnWidths;

      const date = new Date();
      const timestamp = `${date.getFullYear()}${(date.getMonth()+1).toString().padStart(2,'0')}${date.getDate().toString().padStart(2,'0')}`;
      
      // 导出文件
      XLSX.writeFile(workbook, `在途项目列表_${timestamp}.xlsx`);

      // 提示导出成功
      this.$message({
        message: '导出成功',
        type: 'success',
        duration: 2000
      });
    },
    
    initCharts() {
      // 初始化饼图
      this.pieChart = echarts.init(this.$refs.pieChart);
      
      // 计算各类型项目数量
      const projectTypes = {
        '内部项目': this.tableData.filter(p => p.projectType === '内部项目').length,
        '外部项目': this.tableData.filter(p => p.projectType === '外部项目').length,
        '研发项目': this.tableData.filter(p => p.projectType === '研发项目').length
      };

      const pieOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['内部项目', '外部项目', '研发项目']
        },
        series: [{
          name: '项目类型',
          type: 'pie',
          radius: '70%',
          center: ['52%', '50%'], // 饼图水平位置
          data: [
            { value: projectTypes['内部项目'], name: '内部项目' },
            { value: projectTypes['外部项目'], name: '外部项目' },
            { value: projectTypes['研发项目'], name: '研发项目' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      
      this.pieChart.setOption(pieOption);
    },
    
    // 添加更新图表的方法
    updateCharts() {
      if (this.pieChart) {
        this.initCharts();
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    }
  },
  watch: {
    // 监听tableData变化，更新图表
    tableData: {
      handler() {
        this.$nextTick(() => {
          this.updateCharts();
        });
      },
      deep: true
    }
  },
  created() {
    this.getinfo()
  },
  mounted() {
    this.initCharts();
  },
  beforeDestroy() {
    if (this.pieChart) {
      this.pieChart.dispose();
    }
    if (this.lineChart) {
      this.lineChart.dispose();
    }
  }
}
</script>

<style scoped>
.project-doing-container {
  padding: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-item i {
  font-size: 48px;
  margin-right: 20px;
  color: #409EFF;
}

.stat-info {
  flex-grow: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-top: 5px;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
  height: 420px; /* 统一设置卡片高度 */
}

.chart-container {
  height: 300px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
}

.search-filter-section {
  background: #fff;
  padding: 10px;
  padding-top: 0;
  border-radius: 4px;
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: nowrap;
  gap: 10px;
}

.main-table-section {
  background: #fff;
  border-radius: 4px;
  margin-bottom: 50px;
}

.progress-list {
  height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.progress-item {
  margin-bottom: 20px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.progress-item:hover {
  background: #f0f2f5;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.project-name {
  font-weight: bold;
  font-size: 14px;
  color: #303133;
  max-width: 70%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.progress-value {
  color: #409EFF;
  font-weight: bold;
}

.progress-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
}

.project-budget {
  color: #909399;
}

/* 自定义滚动条样式 */
.progress-list::-webkit-scrollbar {
  width: 6px;
}

.progress-list::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.progress-list::-webkit-scrollbar-track {
  background: #f8f9fa;
}

/* 添加分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>









<!-- <script>
import axios from "axios";
import http from "@/api/http";
export default {
  name: "ProjectDoing",
  methods:{
    getinfo(){
      http.get("/api/projects/ongoing")
          .then(res=>{
            this.tableData=res;
            console.log(res)
          })
    },
    searchOngoing(){
      http.get("/api/projects/ongoing/search?keyword="+this.input2)
          .then(res=>{
            this.tableData=res;
            console.log('Search ongoing project: ',res)
          })
    }
  },
  created(){
    this.getinfo()
  },
  data() {
    return {
      input2:'',
      parentsCloums: [ //外层table的表头
        {
          name: "项目名称",
          propName: "projectName",
        }, {
          name: "合同额",
          propName: "contractAmount",
        }, {
          name: "重要程度",
          propName: "importantLevel",
        },{
          name: "预算",
          propName: "budget",
        },{
          name: "项目类别型",
          propName: "projectType",
        },

      ],
      tableData: [], //外层table的数据
    }
  }
}
</script>

<template>
  <div class="shopList">
    <div style="display: flex;justify-content: space-between;align-items: center;">
      <div></div>
      <div></div>
      <div style="width: 200px;margin-right: 80px">
        <el-input
            placeholder="请输入项目名"
            prefix-icon="el-icon-search"
            v-model="input2"
            @keyup.enter.native="searchOngoing">
        </el-input>
      </div>
    </div>
    <el-table :data="tableData" style="width: 100%">
      //对外层的表格表头进行了遍历循环
      <el-table-column
          v-for="(value, key, index) in parentsCloums "
          :label="value.name"
          :prop="value.propName"
          :key="index"
      >
      </el-table-column>
      <el-table-column
          label="进度"
          prop="taskProgress"
      >
        <template slot-scope="scope">
          <el-progress
              type="line"
              :stroke-width="15"
              :percentage=scope.row.taskProgress
          ></el-progress>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.add-button{
  color: white;
  background: cornflowerblue;
  height: 50px;
  width:180px;
  border-radius: 25px;
  margin:10px;
  font-size: 20px;
  border: 0px;
}
</style> -->
